package com.boss.salary.service.impl;

import com.boss.salary.dao.IAgencyInfoDao;
import com.boss.salary.dao.IPersonOperateDao;
import com.boss.salary.entity.AgencyInfo;
import com.boss.salary.entity.AgencyVerify;
import com.boss.salary.service.IRedisService;
import com.boss.salary.service.ISalaryHistoryAsyncService;
import com.singularsys.jep.JepException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

@Service
@EnableAsync
public class SalaryHistoryAsyncServiceImpl implements ISalaryHistoryAsyncService {
    /**
     * 引入日志框架常量
     */
    @Lazy
    private static final Logger logger = LoggerFactory.getLogger(SalaryHistoryAsyncServiceImpl.class);
    private static DateFormat df = new SimpleDateFormat("yyyy-MM");
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IPersonOperateDao personOperateDao;
    @Autowired
    private IAgencyInfoDao agencyInfoDao;

    @Autowired
    private SalaryHistoryServiceImpl salaryHistoryService;
    @Autowired
    private SalaryHistoryAsyncChildrenServiceImpl salaryHistoryAsyncChildrenService;

    /**
     * 缓解月结数据库超时问题通过循环分成小的事务
     * @param year
     * @param province
     * @param agencyIds
     * @param monthMap
     * @param agencyNameMap
     * @param agencyCodeMap
     * @param personOperateUpdateList
     * @throws ParseException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws NoSuchMethodException
     * @throws JepException
     */
    @Async
    @Override

    public  void saveMonthEndAsynchronous(List<AgencyVerify>agencyVerifyEndList, Integer year, String province, List<String> agencyIds, Map<String, String> monthMap, Map<String, String> agencyNameMap, Map<String, String> agencyCodeMap, List<Object[]> personOperateUpdateList, String uuid) throws ParseException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, JepException {
        StringBuffer requestMessage=new StringBuffer();
        DecimalFormat df=new DecimalFormat("0.00");
        logger.info("=======单位月结异步方法开始==============");
        for(int i=0;i<agencyIds.size();i++){
            AgencyInfo agencyName=agencyInfoDao.selectFirstAuthAgencyData(agencyIds.get(i));
            try{
                salaryHistoryAsyncChildrenService.saveMonthEnds(agencyVerifyEndList,year,province,agencyIds.get(i),monthMap,agencyNameMap,agencyCodeMap,personOperateUpdateList,requestMessage);
            }catch (Exception e){
            logger.info("月结后续方法错误：",e);
                requestMessage.append(agencyName.getAgencyName());
        }
            redisService.put(uuid,df.format((float)(i+1)/agencyIds.size()));
            System.out.println(df.format((float)(i+1)/agencyIds.size()));
            if(i+1==agencyIds.size()){
                redisService.del(province+"lunarKnot");
            }
        }
        if(StringUtils.isEmpty(requestMessage.toString())) {
            redisService.put(uuid, "S");
        }else{
            redisService.put(uuid,"F-"+requestMessage.toString());
        }
        logger.info("=======单位月结异步方法结束==============");
    }
    @Async
    @Override
    public  void saveMonthEndAsynchronousDouble(List<AgencyVerify>agencyVerifyDoubleList,Integer year, String province, List<String> agencyIds, Map<String, String> monthMap, Map<String, String> agencyNameMap, Map<String, String> agencyCodeMap, List<Object[]> personOperateUpdateList, String uuid) throws ParseException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, JepException {
        StringBuffer requestMessage=new StringBuffer();
        DecimalFormat df=new DecimalFormat("0.00");
        logger.info("=======单位月结异步方法开始==============");
        for(int i=0;i<agencyIds.size();i++){
            AgencyInfo agencyName=agencyInfoDao.selectFirstAuthAgencyData(agencyIds.get(i));
            try{
            salaryHistoryAsyncChildrenService.saveMonthEndsDouble(agencyVerifyDoubleList,year,province,agencyIds.get(i),monthMap,agencyNameMap,agencyCodeMap,personOperateUpdateList,requestMessage);
            }catch (Exception e){
                logger.info("月结后续方法错误：",e);
                requestMessage.append(agencyName.getAgencyName());
            }
            redisService.put(uuid,df.format((float)(i+1)/agencyIds.size()));
            System.out.println(df.format((float)(i+1)/agencyIds.size()));
            if(i+1==agencyIds.size()){
                redisService.del(province+"lunarKnot");
            }
        }
        if(StringUtils.isEmpty(requestMessage.toString())) {
            redisService.put(uuid, "S");
        }else{
            redisService.put(uuid,"F-"+requestMessage.toString());
        }
        logger.info("=======单位月结异步方法结束==============");
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public  void saveMonthEnds(List<AgencyVerify> agencyVerifyEndList, Integer year, String province, String agencyId, Map<String, String> monthMap, Map<String, String> agencyNameMap, Map<String, String> agencyCodeMap, List<Object[]> personOperateUpdateList, StringBuffer requestMessage)throws Exception {
//
////        try{
//            //Thread.currentThread().sleep(300);
//            // 批量修改单位审核表的上报状态后，增加下个月的初始数据
//            logger.info("==================批量修改审核表数据 Begin ================");
//            salaryHistoryService.batchAgencyVerify(year, province,agencyId, monthMap,agencyNameMap,agencyCodeMap);
//            logger.info("==================批量修改审核表数据 End ================");
//
//            logger.info("==================批量存储单位历史表数据 Begin ================");
//            // 将单位信息存储到历史表
//            salaryHistoryService.batchSaveAgencyHistory(province,agencyId, monthMap);
//            logger.info("==================批量存储单位历史表数据 End ================");
//            logger.info("==================批量存储人员历史表数据 Begin ================");
//            // 将人员信息存储到历史表
//            salaryHistoryService.batchSavePersonHistory(province,agencyId, monthMap);
//            logger.info("==================批量存储人员历史表数据 End ================");
//            logger.info("==================批量存储工资表历史表数据 Begin ================");
//            // 转换工资表数据并添加到历史表
//            salaryHistoryService.batchSaveSalaryHistory(province,agencyId, monthMap,0);
//            logger.info("==================批量存储工资表历史表数据 End ================");
//            logger.info("==================批量存储工资表月初表数据 Begin ================");
//            // 转换工资表数据并添加到历史表
//            salaryHistoryService.batchSaveSalaryMonthBegin(province, agencyId,agencyVerifyEndList);
//            logger.info("==================批量存储工资表月初表数据 End ================");
//            logger.info("==================批量存储工资表月初表数据 Begin ================");
//            //支付回盘信息保存到历史表中，同时清空回盘信息
//            salaryHistoryService.batchPaymentBack(agencyId,monthMap);
//            logger.info("==================批量存储支付回盘数据 End ================");
//            logger.info("==================批量存储银行回盘数据 Begin ================");
//            //银行回盘信息保存到历史表中，同时清空回盘信息
//            salaryHistoryService.batchBankBack(agencyId,monthMap);
//            logger.info("==================批量存储银行回盘数据 End ================");
//            //若自动上报单位不为空则修改上月编报的数据为本月
//            if(!CollectionUtils.isEmpty(personOperateUpdateList)){
//                //将personOperateUpdateList才分 如果id相等走方法
//                for(Object[] personOperate:personOperateUpdateList){
//                    for(int i=0;i<personOperate.length;i++ ){
//                        if(personOperate[i].equals(agencyId)){
//                            // 批量修改自动上报单位上月修改数据状态改为下个月
//                            logger.info("==================批量修改自动上报单位上月修改数据状态改为下个月 Begin ================");
//                            personOperateDao.batchUpdateAutoMonthEnd(personOperateUpdateList);
//                            logger.info("==================批量修改自动上报单位上月修改数据状态改为下个月 End ================");
//                            logger.info("==================批量修改自动上报单位上月附件数据状态改为下个月 Begin ================");
//                            personOperateDao.batchUpdateAutoFile(personOperateUpdateList);
//                            logger.info("==================批量修改自动上报单位上月附件数据状态改为下个月 End ================");
//                        }
//                    }
//                }
//            }
////        }catch (Exception e){
////            logger.info("月结后续方法错误：",e);
//
////        }
//
//    }
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public  void saveMonthEndsDouble(List<AgencyVerify>agencyVerifyDoubleList,Integer year, String province, String agencyId, Map<String, String> monthMap, Map<String, String> agencyNameMap, Map<String, String> agencyCodeMap, List<Object[]> personOperateUpdateList, StringBuffer requestMessage) throws Exception{
//        AgencyInfo agencyName=agencyInfoDao.selectFirstAuthAgencyData(agencyId);
//        int isThirteen=0;
//        for(AgencyVerify agencyVerify:agencyVerifyDoubleList){
//            if(agencyVerify.getAgencyId().equals(agencyId)){
//                isThirteen=agencyVerify.getIsThirteen();
//            }
//        }
////        try{
//            //Thread.currentThread().sleep(300);
//            // 批量修改单位审核表的上报状态后，增加下个月的初始数据 修改成已月结
//            logger.info("==================批量修批次改审核表数据 Begin ================");
//           // salaryHistoryService.batchAgencyVerify(year, province,agencyId, monthMap,agencyNameMap,agencyCodeMap);
//            salaryHistoryService.updatebatchAgencyVerify(agencyId,agencyVerifyDoubleList);
//            //salaryHistoryService.batchAgencyVerify(year, province,agencyId, monthMap,agencyNameMap,agencyCodeMap);
//            logger.info("==================批量修改批次审核表数据 End ================");
//
//            logger.info("==================批量存储批次单位历史表数据 Begin ================");
//            // 将单位信息存储到历史表
//            //salaryHistoryService.batchSaveAgencyHistory(province,agencyId, monthMap);
//            logger.info("==================批量存储批次单位历史表数据 End ================");
//            logger.info("==================批量存储批次人员历史表数据 Begin ================");
//            // 将人员信息存储到历史表
//            //salaryHistoryService.batchSavePersonHistory(province,agencyId, monthMap);
//            //logger.info("==================批量存储批次人员历史表数据 End ================");
//            //logger.info("==================批量存储批次工资表历史表数据 Begin ================");
//            // 转换工资表数据并添加到批次工资中
//            //salaryHistoryService.batchSaveSalaryMonthEndDouble(province,agencyId, monthMap);
//            logger.info("==================批量存储批次工资表数据 End ================");
//            logger.info("==================批量存储批次工资表数据 Begin ================");
//            // 转换工资表数据并添加到历史表
//            salaryHistoryService.batchSaveSalaryHistory(province,agencyId, monthMap,isThirteen);
//            logger.info("==================批量存储批次工资表历史表数据 End ================");
//            logger.info("==================批量存储批次工资表月初表数据 Begin ================");
//            // 转换工资表数据并添加到历史表
//            // 转换工资表数据并添加到历史表
//            salaryHistoryService.batchDeletedSalaryMonthBegin(province, agencyId,isThirteen);
//            logger.info("==================批量存储工资表月初表数据 End ================");
//            logger.info("==================批量存储工资表月初表数据 Begin ================");
//            //支付回盘信息保存到历史表中，同时清空回盘信息
//            salaryHistoryService.batchPaymentBack(agencyId,monthMap);
//            logger.info("==================批量批次存储支付回盘数据 End ================");
//            logger.info("==================批量批次存储银行回盘数据 Begin ================");
//            //银行回盘信息保存到历史表中，同时清空回盘信息
//            salaryHistoryService.batchBankBack(agencyId,monthMap);
//            logger.info("==================批量存储批次银行回盘数据 End ================");
//            logger.info("==================批量存储批次银行回盘数据 Begin ================");
//            salaryHistoryService.deletedDouble(agencyId,monthMap);
//
//            logger.info("==================批量删除批次表数据数据 End ================");
//            logger.info("==================批量删除批次表数据数据 Begin ================");
//
////        }catch (Exception e){
////            logger.info("月结后续方法错误：",e);
////            requestMessage.append(agencyName.getAgencyName());
////        }
//
//    }

}
